package com.kaibes.module.api.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigRegistry;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;

@Component
public class ApiCloseListener implements ApplicationListener<ContextClosedEvent> {

    @Value("${spring.application.name:}")
    private String service;
    @Value("${spring.cloud.nacos.discovery.group:DEFAULT_GROUP}")
    private String group;
    @Autowired
    private ApiClient apiClient;
    @NacosInjected
    private NamingService naming;
    
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        if (event.getSource() instanceof AnnotationConfigRegistry) {
            try {
                if (naming.getAllInstances(service, group).size() < 2)  {
                    apiClient.delete(service);
                }
            } catch (NacosException e) {
                e.printStackTrace();
            }
        }
    }
    
}
